<?php
session_start();
$step = isset($_GET['step']) ? intval($_GET['step']) : 1;
$error = '';
$success = '';

// 定义环境要求
$requirements = [
    'PHP版本 >= 7.4' => version_compare(PHP_VERSION, '7.4.0', '>='),
    'PDO扩展' => extension_loaded('pdo'),
    'PDO MySQL扩展' => extension_loaded('pdo_mysql'),
    'GD扩展' => extension_loaded('gd'),
    'config.php可写' => is_writable('config.php') || !file_exists('config.php'),
];

// 检查是否已安装
if (file_exists('install.lock') && $step != 'finished') {
    die('系统已安装，如需重新安装请删除 install.lock 文件');
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    switch ($step) {
        case 1:
            // 检查环境
            $canContinue = !in_array(false, $requirements);
            if ($canContinue) {
                header('Location: install.php?step=2');
                exit;
            }
            break;
            
        case 2:
            // 数据库配置
            $db_host = $_POST['db_host'] ?? '';
            $db_name = $_POST['db_name'] ?? '';
            $db_user = $_POST['db_user'] ?? '';
            $db_pass = $_POST['db_pass'] ?? '';
            $force_install = isset($_POST['force_install']) ? (bool)$_POST['force_install'] : false;
            
            try {
                // 创建数据库连接
                $dsn = "mysql:host=$db_host;charset=utf8mb4";
                $pdo = new PDO($dsn, $db_user, $db_pass);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                
                // 检查数据库是否存在
                $stmt = $pdo->query("SELECT COUNT(*) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$db_name'");
                $dbExists = (bool)$stmt->fetchColumn();
                
                if ($dbExists) {
                    // 检查admins表是否存在
                    $pdo->exec("USE `$db_name`");
                    $stmt = $pdo->query("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '$db_name' AND TABLE_NAME = 'admins'");
                    $tableExists = (bool)$stmt->fetchColumn();
                    
                    if ($tableExists && !$force_install) {
                        // 存储数据库信息到会话，以便在确认页面使用
                        $_SESSION['db_info'] = [
                            'db_host' => $db_host,
                            'db_name' => $db_name,
                            'db_user' => $db_user,
                            'db_pass' => $db_pass
                        ];
                        header('Location: install.php?step=2&confirm=1');
                        exit;
                    }
                }
                
                // 创建数据库（如果不存在）
                $pdo->exec("CREATE DATABASE IF NOT EXISTS `$db_name` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci");
                $pdo->exec("USE `$db_name`");
                
                // 如果强制安装，先删除所有现有表
                if ($force_install) {
                    $stmt = $pdo->query("SHOW TABLES");
                    $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
                    
                    if (!empty($tables)) {
                        // 禁用外键检查
                        $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
                        
                        foreach ($tables as $table) {
                            $pdo->exec("DROP TABLE `$table`");
                        }
                        
                        // 重新启用外键检查
                        $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
                    }
                }
                
                // 重新连接到新创建的数据库
                $dsn = "mysql:host=$db_host;dbname=$db_name;charset=utf8mb4";
                $pdo = new PDO($dsn, $db_user, $db_pass);
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                
                // 导入SQL文件
                $sql = file_get_contents('install.sql');
                $pdo->exec($sql);
                
                // 更新配置文件
                $config_content = "<?php
session_start();

// 数据库配置
define('DB_HOST', '$db_host');
define('DB_NAME', '$db_name');
define('DB_USER', '$db_user');
define('DB_PASS', '$db_pass');
define('API_KEY', '123');//API密钥 不用动
// 创建PDO实例
try {
    \$pdo = new PDO(
        \"mysql:host=\".DB_HOST.\";dbname=\".DB_NAME.\";charset=utf8mb4\",
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false
        ]
    );
} catch (PDOException \$e) {
    die(\"Database connection failed: \" . \$e->getMessage());
}

// 安全过滤函数
function sanitize(\$data) {
    return htmlspecialchars(trim(\$data), ENT_QUOTES, 'UTF-8');
}";
                
                file_put_contents('config.php', $config_content);
                header('Location: install.php?step=3');
                exit;
            } catch (PDOException $e) {
                $error = '数据库配置错误：' . $e->getMessage();
            }
            break;
            
        case 3:
            // 创建管理员账号
            $admin_user = $_POST['admin_user'] ?? '';
            $admin_pass = $_POST['admin_pass'] ?? '';
            $admin_pass_confirm = $_POST['admin_pass_confirm'] ?? '';
            
            if (strlen($admin_user) < 4) {
                $error = '用户名至少需要4个字符';
            } elseif (strlen($admin_pass) < 6) {
                $error = '密码至少需要6个字符';
            } elseif ($admin_pass !== $admin_pass_confirm) {
                $error = '两次输入的密码不一致';
            } else {
                require_once 'config.php';
                $hashed_password = password_hash($admin_pass, PASSWORD_DEFAULT);
                
                try {
                    $stmt = $pdo->prepare("INSERT INTO admins (username, password) VALUES (?, ?)");
                    $stmt->execute([$admin_user, $hashed_password]);
                    
                    // 创建安装锁定文件
                    file_put_contents('install.lock', date('Y-m-d H:i:s'));
                    
                    header('Location: install.php?step=finished');
                    exit;
                } catch (PDOException $e) {
                    $error = '创建管理员账号失败：' . $e->getMessage();
                }
            }
            break;
    }
}

// 获取确认覆盖数据库的参数
$confirm = isset($_GET['confirm']) ? (bool)$_GET['confirm'] : false;
// 从会话中获取数据库信息
$db_info = $_SESSION['db_info'] ?? [];
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title>安装向导 - 步骤 <?php echo $step; ?></title>
    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <link rel="stylesheet" type="text/css" href="assets/css/materialdesignicons.min.css">
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="assets/css/animate.min.css">
    <link rel="stylesheet" type="text/css" href="assets/css/style.min.css">
    <style>
        body {
            background-color: #f5f5f5;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            padding: 20px;
        }
        .install-container {
            width: 100%;
            max-width: 800px;
        }
        .step-header {
            margin-bottom: 20px;
            text-align: center;
        }
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
        }
        .step-indicator .step {
            flex: 1;
            text-align: center;
            position: relative;
        }
        .step-indicator .step::after {
            content: '';
            position: absolute;
            top: 15px;
            left: 50%;
            width: 100%;
            height: 2px;
            background-color: #e9ecef;
            z-index: 0;
        }
        .step-indicator .step:last-child::after {
            display: none;
        }
        .step-indicator .step .step-icon {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 5px;
            position: relative;
            z-index: 1;
        }
        .step-indicator .step.active .step-icon {
            background-color: #33cabb;
            color: white;
        }
        .step-indicator .step.completed .step-icon {
            background-color: #28a745;
            color: white;
        }
        .step-indicator .step.completed::after {
            background-color: #28a745;
        }
        .step-content {
            background: #fff;
            padding: 30px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="install-container">
        <div class="card">
            <div class="card-header">
                <h4 class="text-center">安装向导</h4>
            </div>
            <div class="card-body">
                <!-- 步骤指示器 -->
                <div class="step-indicator">
                    <div class="step <?php echo $step >= 1 ? 'active' : ''; ?> <?php echo $step > 1 ? 'completed' : ''; ?>">
                        <div class="step-icon">
                            <?php if ($step > 1): ?>
                                <i class="mdi mdi-check"></i>
                            <?php else: ?>
                                1
                            <?php endif; ?>
                        </div>
                        <div class="step-label">环境检查</div>
                    </div>
                    <div class="step <?php echo $step >= 2 ? 'active' : ''; ?> <?php echo $step > 2 ? 'completed' : ''; ?>">
                        <div class="step-icon">
                            <?php if ($step > 2): ?>
                                <i class="mdi mdi-check"></i>
                            <?php else: ?>
                                2
                            <?php endif; ?>
                        </div>
                        <div class="step-label">数据库配置</div>
                    </div>
                    <div class="step <?php echo $step >= 3 ? 'active' : ''; ?> <?php echo $step > 3 || $step == 'finished' ? 'completed' : ''; ?>">
                        <div class="step-icon">
                            <?php if ($step > 3 || $step == 'finished'): ?>
                                <i class="mdi mdi-check"></i>
                            <?php else: ?>
                                3
                            <?php endif; ?>
                        </div>
                        <div class="step-label">管理员设置</div>
                    </div>
                    <div class="step <?php echo $step == 'finished' ? 'active completed' : ''; ?>">
                        <div class="step-icon">
                            <?php if ($step == 'finished'): ?>
                                <i class="mdi mdi-check"></i>
                            <?php else: ?>
                                4
                            <?php endif; ?>
                        </div>
                        <div class="step-label">完成安装</div>
                    </div>
                </div>
                
                <!-- 错误和成功提示 -->
                <?php if ($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong>错误！</strong> <?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong>成功！</strong> <?php echo $success; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <!-- 步骤内容 -->
                <div class="step-content">
                    <?php if ($step == 1): ?>
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">环境检查</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>检查项</th>
                                                <th width="100">状态</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($requirements as $item => $satisfied): ?>
                                            <tr>
                                                <td><?php echo $item; ?></td>
                                                <td>
                                                    <?php if ($satisfied): ?>
                                                        <span class="text-success"><i class="mdi mdi-check-circle"></i> 通过</span>
                                                    <?php else: ?>
                                                        <span class="text-danger"><i class="mdi mdi-close-circle"></i> 未通过</span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <form method="post" class="text-center mt-4">
                                    <button type="submit" class="btn btn-primary">下一步 <i class="mdi mdi-arrow-right"></i></button>
                                </form>
                            </div>
                        </div>
                        
                    <?php elseif ($step == 2 && $confirm): ?>
                        <!-- 数据库覆盖确认 -->
                        <div class="card">
                            <div class="card-header bg-warning text-white">
                                <h5 class="mb-0"><i class="mdi mdi-alert"></i> 数据库覆盖确认</h5>
                            </div>
                            <div class="card-body">
                                <div class="alert alert-danger">
                                    <h5><i class="mdi mdi-alert-circle"></i> 警告！</h5>
                                    <p>检测到数据库 <strong><?php echo htmlspecialchars($db_info['db_name'] ?? ''); ?></strong> 中已存在系统表，继续安装将会覆盖现有数据！</p>
                                    <p>这个操作不可逆，所有现有数据将被删除。</p>
                                </div>
                                
                                <form method="post" class="text-center mt-4">
                                    <input type="hidden" name="db_host" value="<?php echo htmlspecialchars($db_info['db_host'] ?? ''); ?>">
                                    <input type="hidden" name="db_name" value="<?php echo htmlspecialchars($db_info['db_name'] ?? ''); ?>">
                                    <input type="hidden" name="db_user" value="<?php echo htmlspecialchars($db_info['db_user'] ?? ''); ?>">
                                    <input type="hidden" name="db_pass" value="<?php echo htmlspecialchars($db_info['db_pass'] ?? ''); ?>">
                                    <input type="hidden" name="force_install" value="1">
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <a href="install.php?step=2" class="btn btn-secondary w-100">
                                                <i class="mdi mdi-arrow-left"></i> 返回修改
                                            </a>
                                        </div>
                                        <div class="col-md-6">
                                            <button type="submit" class="btn btn-danger w-100">
                                                <i class="mdi mdi-database-remove"></i> 确认覆盖并继续
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        
                    <?php elseif ($step == 2): ?>
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">数据库配置</h5>
                            </div>
                            <div class="card-body">
                                <form method="post">
                                    <div class="mb-3">
                                        <label for="db_host" class="form-label">数据库主机</label>
                                        <input type="text" id="db_host" name="db_host" class="form-control" value="localhost" required>
                                        <div class="form-text">通常为localhost或127.0.0.1</div>
                                    </div>
                                    <div class="mb-3">
                                        <label for="db_name" class="form-label">数据库名</label>
                                        <input type="text" id="db_name" name="db_name" class="form-control" required>
                                        <div class="form-text">如果不存在将自动创建</div>
                                    </div>
                                    <div class="mb-3">
                                        <label for="db_user" class="form-label">数据库用户名</label>
                                        <input type="text" id="db_user" name="db_user" class="form-control" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="db_pass" class="form-label">数据库密码</label>
                                        <input type="password" id="db_pass" name="db_pass" class="form-control" required>
                                    </div>
                                    <div class="text-center mt-4">
                                        <a href="install.php?step=1" class="btn btn-secondary me-2"><i class="mdi mdi-arrow-left"></i> 上一步</a>
                                        <button type="submit" class="btn btn-primary">下一步 <i class="mdi mdi-arrow-right"></i></button>
                                    </div>
                                </form>
                            </div>
                        </div>
                        
                    <?php elseif ($step == 3): ?>
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">创建管理员账号</h5>
                            </div>
                            <div class="card-body">
                                <form method="post">
                                    <div class="mb-3">
                                        <label for="admin_user" class="form-label">管理员用户名</label>
                                        <input type="text" id="admin_user" name="admin_user" class="form-control" required>
                                        <div class="form-text">用户名至少需要4个字符</div>
                                    </div>
                                    <div class="mb-3">
                                        <label for="admin_pass" class="form-label">管理员密码</label>
                                        <input type="password" id="admin_pass" name="admin_pass" class="form-control" required>
                                        <div class="form-text">密码至少需要6个字符</div>
                                    </div>
                                    <div class="mb-3">
                                        <label for="admin_pass_confirm" class="form-label">确认密码</label>
                                        <input type="password" id="admin_pass_confirm" name="admin_pass_confirm" class="form-control" required>
                                        <div class="form-text">请再次输入密码</div>
                                    </div>
                                    <div class="text-center mt-4">
                                        <a href="install.php?step=2" class="btn btn-secondary me-2"><i class="mdi mdi-arrow-left"></i> 上一步</a>
                                        <button type="submit" class="btn btn-primary">完成安装 <i class="mdi mdi-check"></i></button>
                                    </div>
                                </form>
                            </div>
                        </div>
                        
                    <?php elseif ($step == 'finished'): ?>
                        <div class="card">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0"><i class="mdi mdi-check-circle"></i> 安装完成</h5>
                            </div>
                            <div class="card-body text-center">
                                <div class="mb-4">
                                    <i class="mdi mdi-check-circle-outline text-success" style="font-size: 5rem;"></i>
                                </div>
                                <h4 class="text-success mb-3">恭喜，系统已经成功安装！</h4>
                                <p class="mb-4">为了安全起见，请删除 <code>install.php</code> 和 <code>install.sql</code> 文件。</p>
                                <div class="mt-4">
                                    <a href="admin/" class="btn btn-primary me-2"><i class="mdi mdi-login"></i> 进入管理后台</a>
                                    <a href="index.php" class="btn btn-info"><i class="mdi mdi-home"></i> 访问首页</a>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <div class="card-footer text-center">
                <p class="mb-0">© <?php echo date('Y'); ?> 版权所有</p>
            </div>
        </div>
    </div>

    <script type="text/javascript" src="assets/js/jquery.min.js"></script>
    <script type="text/javascript" src="assets/js/popper.min.js"></script>
    <script type="text/javascript" src="assets/js/bootstrap.min.js"></script>
</body>
</html> 